package com.woniu.customer.controller;

import com.woniu.common.dto.LoginDto;
import com.woniu.common.entity.AdmCustomer;
import com.woniu.common.entity.Result;
import com.woniu.customer.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@RestController
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    RedisTemplate redisTemplate;
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto, HttpServletResponse response){
        System.out.println(loginDto);
        return loginService.login(loginDto,response);
    }
    //  发送邮箱验证码
    @PostMapping("/mailcode")
    public Result mailcode(@RequestBody LoginDto loginDto){
        //  生成6位验证码
        int code = 100000 + new Random().nextInt(900000);
        String emailcode = String.valueOf(code);
        System.out.println("邮箱验证码为："+emailcode);
        System.out.println("用户名为："+loginDto.getAaname());
        // 发送邮箱验证码
        loginService.sendEmail(loginDto.getAaname(),emailcode);
        //  将验证码存入redis，并且设置2分钟过期时长
        redisTemplate.opsForValue().set("emailcode:"+loginDto.getAaname(), emailcode, 2, TimeUnit.MINUTES);
        return Result.ok();
    }
    //  注册用户
    @PostMapping("/add")
    public Result addCustomer(@RequestBody AdmCustomer admCustomer, HttpServletRequest request) {
        loginService.addCustomer(admCustomer);
        return Result.ok("添加成功");
    }
    @GetMapping("/main")
    public Result main(HttpServletRequest request,HttpServletResponse response){
        System.out.println("客户id："+request.getHeader("userid"));
        return Result.ok();
    }
    //  处理认证失败异常
    @GetMapping("/expiredJwtException")
    public void expiredJwtException(HttpServletRequest request){
        IllegalStateException exception = (IllegalStateException) request.getAttribute("expiredJwtException");
        throw exception;
    }
    //  查询用户信息
    @PostMapping("/findcustomer")
    public Result<AdmCustomer> findCustomer(HttpServletRequest request) {
        int userid = Integer.parseInt(request.getHeader("userid"));
        AdmCustomer customer = loginService.getCustomerById(userid);
        return new Result<>(200,null,customer);
    }
}
